/*
 * Copyright (c) 2008 by 1eEurope (Switzerland) AG, Thalwil
 *
 * Customer:	1eEurope (Switzerland) AG
 * Project:		BKS
 * Created:		30.09.2008, WBL
 *
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Collections.Specialized;
using System.Xml;
using System.IO;
using System.Xml.Xsl;
using System.Web.UI.WebControls;
using By1eEurope.BKS.Tools.Utils;

namespace By1eEurope.BKS.Controls
{
    /// <summary>
    /// Intelligent LanguageSwitch Control. An XML structure of the related items of the current page is built and is rendered with a specified XSLT
    /// </summary>
    public class LanguageControl : WebControl
    {
        private string xsltPath;
        /// <value>
        /// Path to the XSLT, that receives and tranforms the following XML structure to the desired HTML-Output:
        /// <![CDATA[<Variations>
        ///   <Variation Title="de-CH" DisplayName="D" IsSource="True" Url="/de-ch/seiten/register.aspx" IsCurrent="True" /> 
        ///   <Variation Title="fr-CH" DisplayName="F" IsSource="False" Url="/fr-CH/Pages/Register.aspx" IsCurrent="False" /> 
        ///   <Variation Title="it-CH" DisplayName="I" IsSource="False" Url="/it-CH/Pagine/Register.aspx" IsCurrent="False" /> 
        /// </Variations>]]>
        /// </value>
        public string XsltPath
        {
            set { this.xsltPath = value; }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode root = xmlDoc.CreateElement("Variations");
            xmlDoc.AppendChild(root);
            
            SPContext context = SPContext.Current;
            PublishingWeb currentPubWeb = null;
            PublishingWeb pubWebInVar = null;
            try
            {
                PublishingPage currentPubPage = null;
                if (PublishingPage.IsPublishingPage(context.ListItem))
                    currentPubPage = PublishingPage.GetPublishingPage(context.ListItem);
                else if (PublishingWeb.IsPublishingWeb(context.Web))
                    currentPubWeb = PublishingWeb.GetPublishingWeb(context.Web);

                foreach (VariationLabel varLbl in Variations.Current.UserAccessibleLabels)
                {
                    XmlNode variation = xmlDoc.CreateElement("Variation");

                    XmlAttribute varCode = xmlDoc.CreateAttribute("Title");
                    varCode.Value = varLbl.Title;
                    variation.Attributes.Append(varCode);

                    XmlAttribute varDispName = xmlDoc.CreateAttribute("DisplayName");
                    varDispName.Value = varLbl.DisplayName;
                    variation.Attributes.Append(varDispName);

                    XmlAttribute varIsSource = xmlDoc.CreateAttribute("IsSource");
                    varIsSource.Value = varLbl.IsSource.ToString();
                    variation.Attributes.Append(varIsSource);

                    if (context.Web.Url.StartsWith(varLbl.TopWebUrl))
                    {
                        XmlAttribute url = xmlDoc.CreateAttribute("Url");
                        url.Value = this.Page.Request.Url.PathAndQuery;
                        variation.Attributes.Append(url);

                        XmlAttribute varIsCurrent = xmlDoc.CreateAttribute("IsCurrent");
                        varIsCurrent.Value = "True";
                        variation.Attributes.Append(varIsCurrent);
                    }
                    else if (currentPubPage != null)
                    {
                        PublishingPage pubPageInVar = currentPubPage.GetVariation(varLbl);
                        if (pubPageInVar != null)
                        {
                            XmlAttribute url = xmlDoc.CreateAttribute("Url");
                            pubWebInVar = pubPageInVar.PublishingWeb;
                            url.Value = pubWebInVar.Uri.AbsolutePath + "/" + pubPageInVar.Url;
                            variation.Attributes.Append(url);

                            XmlAttribute varIsCurrent = xmlDoc.CreateAttribute("IsCurrent");
                            varIsCurrent.Value = "False";
                            variation.Attributes.Append(varIsCurrent);
                        }
                        else
                        {
                            currentPubWeb = currentPubPage.PublishingWeb;
                            pubWebInVar = currentPubWeb.GetVariation(varLbl);
                            if (pubWebInVar != null)
                            {
                                XmlAttribute url = xmlDoc.CreateAttribute("Url");
                                url.Value = pubWebInVar.Uri.AbsolutePath;
                                variation.Attributes.Append(url);

                                XmlAttribute varIsCurrent = xmlDoc.CreateAttribute("IsCurrent");
                                varIsCurrent.Value = "False";
                                variation.Attributes.Append(varIsCurrent);
                            }
                        }
                    }
                    else if (currentPubWeb != null)
                    {
                        pubWebInVar = currentPubWeb.GetVariation(varLbl);
                        if (pubWebInVar != null)
                        {
                            XmlAttribute url = xmlDoc.CreateAttribute("Url");
                            url.Value = pubWebInVar.Url;
                            variation.Attributes.Append(url);

                            XmlAttribute varIsCurrent = xmlDoc.CreateAttribute("IsCurrent");
                            varIsCurrent.Value = "False";
                            variation.Attributes.Append(varIsCurrent);
                        }
                    }
                    root.AppendChild(variation);
                }

                XslCompiledTransform xslt = XmlUtil.GetXsltDocument(context.Web, this.xsltPath);
                XsltArgumentList xsltArgs = new XsltArgumentList();
                xsltArgs.AddParam("datetime", "", DateTime.Now.ToLongDateString());
                xsltArgs.AddParam("guid", "", Guid.NewGuid().ToString());
                StringBuilder stringBuilder = XmlUtil.TransformXslt(xslt, root.OuterXml,xsltArgs);
                writer.Write(stringBuilder.ToString());
            }
            finally
            {
                if (currentPubWeb != null)
                    currentPubWeb.Close();

                if (pubWebInVar != null)
                    pubWebInVar.Close();
            }
        }
    }
}
